<!--单位选择-->
<script setup>
import CustomPopup from '@/components/Popups/CustomPopup.vue'

const props = defineProps({
  title: {
    type: String,
    default: '请选择'
  },
  height: {
    type: String,
    default: '30%'
  },
  show: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default: () => []
  },
  options: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  showButton: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:model-value', 'update:show', 'confirm'])
const showPopup = computed({
  get() {
    return props.show
  },
  set(val) {
    emits('update:show', val)
  }
})

const selectedList = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:model-value', val)
    if (!props.showButton) {
      emits('update:show', false)
      emits('confirm', val)
    }
  }
})

const toggleState = (item) => {
  // 多选
  if (props.multiple) {
    const index = selectedList.value.findIndex(
      (selectedItem) => selectedItem.value === item.value
    )
    if (index !== -1) {
      selectedList.value.splice(index, 1)
    } else {
      // 如果未选中，则添加到已选列表
      selectedList.value.push(item)
    }
  } else {
    selectedList.value = [item]
  }
}
const isActive = (item) => {
  return (
    selectedList.value.findIndex(
      (selectedItem) => selectedItem.value === item.value
    ) > -1
  )
}

const clearSelectedList = () => {
  selectedList.value = [props.options[0]]
  emits('confirm', selectedList.value)
}

const handleConfirm = () => {
  showPopup.value = false
  emits('confirm', selectedList.value)
}
</script>

<template>
  <CustomPopup
    :show.sync="showPopup"
    :height="height"
    :footer="showButton"
    :title="title"
    cancelText="重置"
    confirmText="确定"
    @cancel="clearSelectedList"
    @confirm="handleConfirm"
  >
    <ul
      class="w-full relative h-auto box-border flex gap-12px justify-center py-30px flex-wrap select-none items-center content-start">
      <li
        v-for="item in options"
        :key="item.value"
        :class="{
          'active': isActive(item),
          'disabled': item.disabled
        }"
        class="item w-100px h-32px rounded-4px box-border border-solid border-1px border-#C8C9CC py-9px text-14px font-400 leading-14px text-#54565C text-align-center"
        @click="toggleState(item)"
      >
        {{ item.label }}
      </li>
    </ul>
  </CustomPopup>
</template>

<style lang="less" scoped>

li.active {
  color: #ffffff;
  background-color: #36b374;
}

li.disabled {
  color: #999999;
}
</style>
